package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 自动调用与当前类Test在同一个目录下的被@AutoRun标注的方法
 */
public class Test1 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        File dir = new File(
                Test1.class.getResource(".").toURI()
        );
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File file : subs) {
            String fileName = file.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName("reflect." + className);
            if (!cls.isAnnotation()){ //判断该类对象是否是一个注解，不是注解才实例化
                Object o = cls.newInstance();
                System.out.println("实例化："+cls.getName());
                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods){
                    if (method.isAnnotationPresent(AutoRun.class)){
                        method.invoke(o);
                    }
                }
            }

        }
    }
}
